import React from "react";
import styles from "@styles/login.module.scss";
import classNames from "classnames";
import { useEffect } from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, SubmitHandler } from "react-hook-form";
import { Toast } from "antd-mobile";
import useCountDown from "@hooks/useCountDown";
import { useSendMsgCodeMutation } from "@store/apiSlice/authApiSlice";
import { useLoginByMsgCodeMutation } from "@store/apiSlice/authApiSlice";
import { useTypedDispatch } from "@store/index";
import { useNavigate } from "react-router-dom";
import { saveAuth } from "@store/slices/authSlice";
export interface FormState {
  mobile: string;
  code: string;
  isAgree: boolean;
}
const schema = z.object({
  mobile: z
    .string({
      invalid_type_error: "手机号参数类型错误",
      required_error: "请检查手机号字段名称是否正确",
    })
    .min(1, "请输入手机号")
    .regex(/^1[3-9]\d{9}$/, "手机号格式错误"),
  code: z
    .string({
      invalid_type_error: "验证码参数类型错误",
      required_error: "请检查验证码字段名称是否正确",
    })
    .length(6, "验证码格式错误"),
  isAgree: z.literal(true, {
    errorMap: () => ({ message: "请勾选协议" }),
  }),
});
export default function Message() {
  const {
    register,
    formState: { errors, isValid },
    handleSubmit,
  } = useForm<FormState>({
    // 在用户输入的过程中实时触发验证
    mode: "onChange",
    // 状态默认值
    defaultValues: { mobile: "", code: "" },
    // 设置表单验证器
    resolver: zodResolver(schema),
  });
  useEffect(() => {
    if (typeof errors.isAgree !== "undefined") {
      Toast.show({ content: "请勾选同意协议" });
    }
  }, [errors.isAgree]);
  // 表单提交
  var onSubmit: SubmitHandler<FormState> = (formState) => {
    console.log(formState);
  };
    // 表单验证对象
    const { getFieldState, getValues } = useForm<FormState>();
    // 用于发送手机验证码
  const [sendMsgCodeRequest] = useSendMsgCodeMutation();
   // 用于倒计时
   const { seconds, start, isActive } = useCountDown();
    // 发送手机验证码
  const sendMsgCodeEventHandler = () => {
    // 如果正在倒计时, 阻止代码继续运行
    if (isActive) return;
    // 获取手机号字段状态
    const { isTouched, error } = getFieldState("mobile");
    // 判断用户是否输入了手机号
    if (isTouched && typeof error === "undefined") {
      // 如果用户输入了正确格式的手机号
      // 执行发送手机验证码的请求
      sendMsgCodeRequest({ mobile: getValues("mobile"), type: "login" })
        .unwrap()
        .then((response) => {
          // 发送验证码失败, 比如参数类型错误、用户不存在、验证码已存在
          if (
            typeof response.success !== "undefined" &&
            response.success === false
          ) {
            // 用户提示
            Toast.show({ content: response.message });
          } else {
            // 开启倒计时
            start(60);
            // 用户提示
            Toast.show({ content: "手机验证码发送成功" });
          }
        })
        .catch(() => {
          // 发送验证码失败, 比如没有网络
          Toast.show({ content: "手机验证码发送失败" });
        });
    } else {
      // 用户没有输入手机号或没有输入正确格式的手机号
      Toast.show({ content: "请输入正确格式的手机号" });
    }
  };
    // 用于短信登录
    const [loginByMsgCode] = useLoginByMsgCodeMutation();
      // 获取 dispatch 方法
  const dispatch = useTypedDispatch();
    // 获取路由信息对象
    const navigate = useNavigate();
    // 表单提交
  var onSubmit: SubmitHandler<FormState> = ({ mobile, code }) => {
    loginByMsgCode({ mobile, code })
      .unwrap()
      .then((response) => {
        // 登录失败
        if (
          typeof response.success !== "undefined" &&
          response.success === false
        ) {
          return Toast.show({ content: response.message });
        }
        // 登录成功, 保存用户登录凭据
        dispatch(saveAuth(response.data));
        // 消息提示
        Toast.show({
          content: "登录成功",
          afterClose: () => {
            // 跳转到个人中心页面
            navigate("/personal");
          },
        });
      });
    };
  return (
    <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
    <input {...register("mobile")} />
    {errors.mobile && <p className={styles.msg}>{errors.mobile.message}</p>}
    <input {...register("code")} />
    <input type="checkbox" {...register("isAgree")} />
    {errors.code && <p className={styles.msg}>{errors.code.message}</p>}
    <input {...register("isAgree")} />
    <button className={classNames(styles.submit, { [styles.disabled]: !isValid })}>登录</button>

  </form>
  
  );
}